package demo.mvc.views.main
{
	import demo.mvc.Notifications;
	import demo.mvc.models.AccountModel;
	import demo.mvc.views.login.LoginView;
	
	import com.gamefx.mvc.Facade;
	import com.gamefx.mvc.View;
	import com.gamefx.mvc.classes.Notification;
	
	import flash.events.MouseEvent;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	public class MainView extends View
	{
		[Inject]
		public var accountModel:AccountModel;

		private var ui:MainUI;

		public function MainView(viewName:String=null, viewComponent:Object=null)
		{
			super(viewName, viewComponent);
		}
		
		override public function onRegister():void
		{
			super.onRegister();
			
			ui = new MainUI();
			setViewComponent(ui);
			PopUpManager.addPopUp(ui, Test_Mvc.mainState);
			PopUpManager.centerPopUp(ui);
			
			handler(ui.btnLogout, MouseEvent.CLICK, btnLogout);
			
			subscribe(Notifications.MSG_ACCOUNT_LOGOUT, logoutResultHandler);
		}
		
		override public function onRemove():void
		{
			super.onRemove();
			
			PopUpManager.removePopUp(ui);
		}
		
		private function btnLogout(event:MouseEvent):void
		{
			Alert.show("您确定要退出游戏吗？", "", Alert.YES|Alert.CANCEL, null, alert_closeHandler); 
			
			function alert_closeHandler(event:CloseEvent):void
			{
				if (event.detail == Alert.YES)
				{
					accountModel.logout();
				}
			}
		}
		
		private function logoutResultHandler(notification:Notification):void
		{
			var result:int = notification.getBody() as int;
			
			if (result == 0)
			{
				facade.sendNotification(Notifications.CMD_SCENE_GOTO, Facade.Name(LoginView));
			}
			else
			{
				Alert.show("退出游戏失败！");
			}
		}
	}
}